import React, { Component, useRef, useState } from 'react';
import avatar from '../images/avatar.png'; // 导入图片

// 函数组件
export const Forms = (props) => {
  // 引入页面状态
  const [txt, setText] = useState('xxx');

  // 创建ref变量
  const txtRef = useRef(null);

  // 评论输入变化
  const handleTxtChange = (e) => {
    setText(e.target.value);
  };
  // 发表评论
  const handleSubmit = () => {
    // 1 向父组件传值
    props.handleAddComment(txt);
    // 2 清空本组件的txt
    setText('');
    // 3 设置光标
    txtRef.current.focus();
  };

  return (
    <div className="comment-send-container">
      <div>
        <img className="user-head" src={avatar} alt="头像" />
      </div>
      <div className="comment-send">
        <div className="textarea-container">
          <textarea
            ref={txtRef}
            cols="80"
            rows="5"
            placeholder="发条友善的评论"
            value={txt}
            onChange={handleTxtChange}
            className="ipt-txt"
          />

          <button className="comment-submit" onClick={handleSubmit}>
            发表评论
          </button>
        </div>
        <div className="comment-emoji">
          <i className="face"></i>
          <span className="text">表情</span>
        </div>
      </div>
    </div>
  );
};

// 类组件
export class Forms1 extends Component {
  // 表单组件自生的状态
  state = {
    txt: 'xxx',
  };

  // 表单ref
  txtRef = React.createRef();

  // 评论输入变化
  handleTxtChange = (e) => {
    this.setState({
      txt: e.target.value,
    });
  };

  handleSubmit = () => {
    // 1 向父组件传值
    this.props.handleAddComment(this.state.txt);
    // 2 清空本组件的txt
    this.setState({
      txt: '',
    });
    // 3 设置光标
    this.txtRef.current.focus();
  };

  render() {
    console.log(this.state);
    return (
      <div className="comment-send-container">
        <div>
          <img className="user-head" src={avatar} alt="头像" />
        </div>
        <div className="comment-send">
          <div className="textarea-container">
            <textarea
              ref={this.txtRef}
              cols="80"
              rows="5"
              placeholder="发条友善的评论"
              value={this.state.txt}
              onChange={this.handleTxtChange}
              className="ipt-txt"
            />
            <button className="comment-submit" onClick={this.handleSubmit}>
              发表评论
            </button>
          </div>
          <div className="comment-emoji">
            <i className="face"></i>
            <span className="text">表情</span>
          </div>
        </div>
      </div>
    );
  }
}
